package com.kku;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class DietListAdapter extends BaseAdapter{

	private Context m_Context = null;
	private JSONArray jsonArrayObj = null;
	private final int resId;

	public DietListAdapter(Context context, int textViewResourceId, JSONArray objects) {
		m_Context = context;
		jsonArrayObj = objects;
		resId = textViewResourceId;
		// TODO Auto-generated constructor stub
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		DietListHolder holder;
		View row = convertView;
		if (row == null) {
			LayoutInflater inflator = (LayoutInflater) m_Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			row = inflator.inflate(resId, null);

			holder = new DietListHolder();

			holder.mainText = (TextView) row.findViewById(R.id.main_text);
			holder.subText = (TextView) row.findViewById(R.id.sub_text);

			row.setTag(holder);
		} else {
			holder = (DietListHolder) row.getTag();
		}

		JSONObject item = new JSONObject();
		try {
			item = (JSONObject) jsonArrayObj.get(position);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			holder.mainText.setText(item.getString("title"));
			holder.subText.setText(item.getString("kcal"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return row;
	}

	class DietListHolder {
		TextView mainText;
		TextView subText;
	}

	public int getCount() {
		// TODO Auto-generated method stub
		return jsonArrayObj.length();
	}

	public Object getItem(int position) {
		// TODO Auto-generated method stub
		try {
			return jsonArrayObj.get(position);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

}
